package org.tloss.web.editor.message.editors;

import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.PropertyDescriptor;
import org.tloss.web.editor.enity.editors.JavaClassPropertyDescriptor;
import org.tloss.web.editor.model.Field;
import org.tloss.web.editor.utils.Constants;

public class FieldElement implements IWorkbenchAdapter, IAdaptable {
	private static final String PROPERTY_TYPE = "TYPE";
	private static final String IS_COLLECTION = "IS_COLLECTION";

	Field field;
	IResourceChangeListener listener;

	public void setField(Field field) {
		this.field = field;
	}

	public IResourceChangeListener getListener() {
		return listener;
	}

	public void setListener(IResourceChangeListener listener) {
		this.listener = listener;
	}

	public Field getField() {
		return field;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object getAdapter(Class adapter) {

		if (adapter == IWorkbenchAdapter.class)
			return this;
		if (adapter == IPropertySource.class)
			return new FieldProperties(this);
		return null;
	}

	@Override
	public Object[] getChildren(Object o) {

		return Constants.EMPTY_ARRAY;
	}

	@Override
	public ImageDescriptor getImageDescriptor(Object object) {
		return Constants.FIELD_DESCRIPTOR;

	}

	@Override
	public String getLabel(Object o) {

		return field.getName();
	}

	@Override
	public Object getParent(Object o) {
		return null;
	}

	public void firePropertyChanged(String propName, Object value) {
		if (IS_COLLECTION.equals(propName)) {
			field.setIsCollection((Boolean) value);
		}
		if (PROPERTY_TYPE.equals(propName)) {
			field.setType((String) value);
		}
	}

	public Object getProperty(String name) {
		if (IS_COLLECTION.equals(name)) {
			return field.getIsCollection() != null ? field.getIsCollection()
					: Boolean.FALSE;
		}
		if (PROPERTY_TYPE.equals(name)) {
			return field.getType() != null ? field.getType() : "";
		}
		return "";
	}

	private PropertyDescriptor type = new JavaClassPropertyDescriptor(
			PROPERTY_TYPE, "Type");
	private PropertyDescriptor isCollection = new PropertyDescriptor(
			IS_COLLECTION, "Collection") {
		public CellEditor createPropertyEditor(Composite parent) {
			CheckboxCellEditor cellEditor = new CheckboxCellEditor(parent);
			return cellEditor;
		};
	};

	private IPropertyDescriptor[] descriptors = new IPropertyDescriptor[] {
			type, isCollection };

	public IPropertyDescriptor[] getPropertyDescriptors() {
		// TODO Auto-generated method stub
		return descriptors;
	}

}
